﻿namespace PlugNT.Common.Http
{
    using System;
    using System.Collections;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;

    public class FileModule : IHttpModule
    {
        private void Application_BeginRequest(object sender, EventArgs e)
        {
            SiteUrls siteurls = SiteUrls.GetSiteUrls();
            if (siteurls.Enable)
            {
                HttpContext context = ((HttpApplication) sender).Context;
                string requestPath = context.Request.Path.ToLower();
                ArrayList urls = siteurls.Urls;
                foreach (SiteUrls.URLRewrite url in urls)
                {
                    if (Regex.IsMatch(requestPath, url.Pattern, RegexOptions.IgnoreCase))
                    {
                        string qString = siteurls.CheckRequestArgs ? this.GetUrlPath(context.Request, url.QueryString) : url.QueryString;
                        string newUrl = Regex.Replace(context.Request.Path, url.Pattern, qString, RegexOptions.IgnoreCase);
                        context.RewritePath("/" + url.Page, string.Empty, newUrl);
                        return;
                    }
                }
                context.RewritePath("/" + requestPath);
            }
        }

        private void Application_EndRequest(object source, EventArgs e)
        {
        }

        public void Dispose()
        {
        }

        private string GetUrlPath(HttpRequest request, string fiterQueryString)
        {
            StringBuilder sb = new StringBuilder();
            fiterQueryString = fiterQueryString.Replace(" ", "").Trim();
            if (fiterQueryString == "")
            {
                foreach (string qstring in request.QueryString.AllKeys)
                {
                    sb.Append("&" + qstring + "=" + request.QueryString[qstring]);
                }
            }
            else
            {
                foreach (string qstring in request.QueryString.AllKeys)
                {
                    if (!("&" + fiterQueryString).Contains("&" + qstring + "="))
                    {
                        sb.Append("&" + qstring + "=" + request.QueryString[qstring]);
                    }
                }
            }
            return ((fiterQueryString == "") ? sb.ToString().Trim(new char[] { '&' }) : (fiterQueryString + sb.ToString()));
        }

        public void Init(HttpApplication application)
        {
            application.BeginRequest += new EventHandler(this.Application_BeginRequest);
            application.EndRequest += new EventHandler(this.Application_EndRequest);
        }
    }
}

